<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { router } from "@/router";
import IpChart from "./ipchart.vue";
import Gather from "../../gather/index.vue";
import { get_scan_tactics, delete_scan_tactics } from "@/api/tactics";
import { message } from "@/utils/message";

defineOptions({
  name: "scantactics",
});

const formInline = reactive({
  tacticsName: "",
  tacticsDesc: "",
  tacticsId: "",
  creater: "",
  createTime: "",
});

const createTaskForm = reactive({
  taskType: "",
  taskName: "",
  taskRegion: "",
  startTime: "", //启动时间
  linkTactics: "", //关联策略
  cron: "", //cron表达式
  monthDay: "",
  weekDay: "",
});

const createTaskRules = reactive<FormRules>({
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  taskRegion: [
    {
      required: true,
      message: "请填写资产范围",
      trigger: "blur",
    },
  ],
  taskType: [
    {
      required: true,
      message: "请选择一个任务类别",
      trigger: "change",
    },
  ],
  linkTactics: [
    {
      required: true,
      message: "请关联策略",
      trigger: "change",
    },
  ],
  startTime: [
    {
      // type: "array",
      required: true,
      message: "请选择日期区间",
      trigger: "change",
      // fields: {
      //   // tpye类型试情况而定,所以如果返回的是date就改成date,如果返回的是string就改成string
      //   0: { type: "date", required: true, message: "请选择开始日期" },
      //   1: { type: "date", required: true, message: "请选择结束日期" }
      // }
    },
  ],
});

const tableData = reactive({
  page: 1,
  size: 10,
  total: 11,
  items: [
    // {
    //   scope_group_name: "test",
    //   scope_type: "ip",
    //   scope: "111. 111. 111. 112, 12. 12. 12. 12,13.13.13.13",
    //   scope_array: ["111. 111. 111.112", "12. 12. 12.12", "13.13.13.13"],
    //   black_scope: null,
    //   black_scope_array: [],
    //   scope_id: "65994d1b8dbf870043af437c"
    // },
  ],
});

const showCreateTaskDialog = ref(false);

let allTactics = reactive([]);
let selectTableArr = reactive([]);

const currentPage = ref(1); // 当前页码
const pageSize = ref(15); // 每页显示的条数
const totalTabalData = ref(0); // 总条数

const indexMethod = (index) => {
  // table的index属性为方法时 序号从0开始
  // 序号加1从1开始 + 前面页数的条数总数
  // 前面页数 : 当前页数-1,乘以每页行数
  return index + 1 + (currentPage.value - 1) * 15;
};

const getScanTacticsList = () => {
  get_scan_tactics({
    poc_policy_name: formInline.tacticsName,
    poc_policy_description: formInline.tacticsDesc,
    create_user: formInline.creater,
    scan_policy_id: formInline.tacticsId,
  })
    .then((result) => {
      if (result.code === 2000) {
        console.log(result);
        tableData.items = result.data.policies.slice(0, 15);
        // currentPage.value = result.data.page;
        totalTabalData.value = result.data.total;
        allTactics = result.data.policies;
      }
    })
    .catch((err) => {});
};

const deleteScanTactics = (type, row) => {
  let scan_policy_id = [];
  if (type === "single") {
    scan_policy_id = [row.scan_policy_id];
  } else {
    if (selectTableArr.length === 0) {
      message("请选中数据进行操作！", {
        type: "error",
      });
      return;
    }
    scan_policy_id = selectTableArr.map((item) => item.scan_policy_id);
  }
  debugger;

  delete_scan_tactics({
    scan_policy_id: scan_policy_id,
  })
    .then((result) => {
      if (result.code === 2000) {
        getScanTacticsList();
      }
    })
    .catch((err) => {});
};

const handleSelectionChange = (val) => {
  selectTableArr = val;
};

const deleteArrTactics = (params) => {};

const changeTableByPage = (params) => {
  tableData.items = allTactics.slice((params - 1) * 15, params * 15);
};

const transType = (row) => {
  // 定义一个变量，根据 poc_config_type，poc_web_type_sub_type 来显示不同的类型
  let type = "";
  if (row.poc_config_type === "web") {
    type += "web扫描";
  } else if (row.poc_config_type === "udp") {
    type += "udp扫描";
  }

  if (row.poc_web_type_sub_type === "poc_level") {
    type += "--漏洞等级";
  }
  if (row.poc_web_type_sub_type === "poc_custom") {
    type += "--自定义poc";
  }
  if (row.poc_web_type_sub_type === "poc_always") {
    type += "--常规poc";
  }
  return type;
};

const openAddTacticsDialog = () => {
  router.push("/scanmg/addtacticsnew");
};

//当前行
const selctRowData = ref({});

const openCreateTaskModal = (index, row) => {
  selctRowData.value = row;
  showCreateTaskDialog.value = !showCreateTaskDialog.value;
};

//下发任务
const createTask = () => {};

onMounted(() => {
  getScanTacticsList();
});
</script>

<template>
  <div>
    <data class="gather-container">
      <Gather class="gather-box-blue" />
    </data>
    <div class="right-container">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <el-form
              :inline="true"
              :model="formInline"
              size="small"
              class="demo-form-inline"
              @submit.prevent
            >
              <el-form-item>
                <el-button type="primary" @click="openAddTacticsDialog"
                  >新建策略</el-button
                >
              </el-form-item>

              <el-form-item label="策略名称">
                <el-input
                  v-model="formInline.tacticsName"
                  placeholder="策略名称"
                  maxlength="30"
                  clearable
                  @keyup.enter.stop="getScanTacticsList"
                >
                  <template #append>
                    <el-button
                      :icon="Search"
                      @click.stop.prevent="getScanTacticsList"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="策略描述">
                <el-input
                  v-model="formInline.tacticsDesc"
                  placeholder="策略描述"
                  maxlength="30"
                  clearable
                  @keyup.enter.stop="getScanTacticsList"
                >
                  <template #append>
                    <el-button
                      :icon="Search"
                      @click.stop.prevent="getScanTacticsList"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="创建人">
                <el-input
                  v-model="formInline.creater"
                  placeholder="创建人"
                  maxlength="30"
                  clearable
                  @keyup.enter.stop="getScanTacticsList"
                >
                  <template #append>
                    <el-button
                      :icon="Search"
                      @click.stop.prevent="getScanTacticsList"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="策略ID">
                <el-input
                  v-model="formInline.tacticsId"
                  placeholder="策略ID"
                  maxlength="30"
                  clearable
                  @keyup.enter.stop="getScanTacticsList"
                >
                  <template #append>
                    <el-button
                      :icon="Search"
                      @click.stop.prevent="getScanTacticsList"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="warning"
                  @click="deleteScanTactics('muilt', [])"
                  >批量删除</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </template>

        <!-- <div class="ip-chart-box">
        <IpChart :chartDatas="tableData" />
      </div> -->

        <el-table
          :data="tableData.items"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            width="50"
            label="序号"
            type="index"
            :index="indexMethod"
          />

          <el-table-column label="名称" prop="poc_policy_name" />
          <el-table-column
            label="描述"
            min-width="300px"
            width="300px"
            prop="poc_policy_description"
          />
          <el-table-column label="扫描类型">
            <template #default="rowscope">
              <span>{{ transType(rowscope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" prop="create_user" />
          <el-table-column label="更新时间" prop="create_time" />
          <el-table-column label="操作">
            <template #default="rowscope">
              <el-button
                size="small"
                type="success"
                class="btn-self-light"
                @click="openCreateTaskModal(rowscope.$index, rowscope.row)"
              >
                下发任务</el-button
              >
              <el-button
                size="small"
                type="primary"
                disabled
                @click="deleteAsset(rowscope.$index, rowscope.row)"
              >
                编辑</el-button
              >
              <el-button
                size="small"
                type="warning"
                @click="deleteScanTactics('single', rowscope.row)"
              >
                删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- :page-sizes="[10, 20, 50]"
        @size-change="getAssetList" -->
        <!-- hide-on-single-page -->
        <el-pagination
          @current-change="changeTableByPage"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="total, prev, pager,next"
          :total="totalTabalData"
          background
        />
      </el-card>

      <el-dialog
        v-model="showCreateTaskDialog"
        :show-close="true"
        destroy-on-close
        width="500px"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass">下发任务</h4>
          </div>
        </template>

        <el-form
          :inline="false"
          :model="createTaskForm"
          :rules="createTaskRules"
          ref="addTaskFormRef"
          class="demo-form-inline"
        >
          <el-form-item label="任务名称" label-width="100px" prop="taskName">
            <el-input
              v-model="createTaskForm.taskName"
              placeholder="任务名称"
              clearable
              class="min-w-input"
              maxlength="30"
            />
          </el-form-item>

          <el-form-item label="目标" label-width="100px" prop="taskRegion">
            <el-input
              v-model="createTaskForm.taskRegion"
              placeholder="请输入域名, 如baidu.com, live.qq.com, 输入多个目标用换行或逗号分隔!"
              class="min-w-input"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              clearable
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div>
            <el-button @click="showCreateTaskDialog = false"> 取消 </el-button>
            <el-button type="primary" @click="createTask">
              <!-- <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon> -->
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

:deep(.el-pagination) {
  justify-content: right;
  margin-top: 10px;
  margin-right: 30px;
}

.gather-container {
  display: block;
  margin: 10px 10px 0 10px;
}

.btn-self-light {
  background: #c6e2ff;
  border-color: #c6e2ff;
  &:hover {
    background: #a9d4ff;
    border-color: #c6e2ff;
  }
}
</style>
